<?php

namespace seecms\lib;

use seecms\See;
use seecms\SeeLang;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Twig\TwigFunction;

class Twig
{

    protected static $instance = null;

    /**
     * @param array $config
     * @return Environment
     */
    public function environment(array $config = []): Environment
    {
        $config = $config ?: See::config()->twig->config;

        $templates = $config['templates'] ?? null;
        if (is_string($templates)) {
            $templates = [$templates];
        }

        $module_view = See::module()->getView();
        if ($module_view) {
            foreach ($module_view as $key => $item) {
                if (!is_dir($item)) {
                    unset($module_view[$key]);
                }
            }
        }

        $templates = array_merge($templates, $module_view);

        $kernel = dirname(__DIR__) . '/view';
        array_unshift($templates, $kernel);

        $loader = new FilesystemLoader($templates);
        $twig = new Environment($loader, $config);

        // 添加读取配置文件函数
        $twig->addFunction(new TwigFunction('_', function ($field) {
            return see_config($field);
        }));
        $twig->addFunction(new TwigFunction('see_config', function ($field) {
            return see_config($field);
        }));

        // 添加多语言函数
        $lang = SeeLang::instance();
        $twig->addFunction(new TwigFunction('__', function ($field) use ($lang) {
            return $lang->get($field);
        }));

        // 路由地址
        $twig->addFunction(new TwigFunction('auth_route', function ($route) {
            return auth_route($route);
        }));

        $twig->addFunction(new TwigFunction('lib', function ($src) {
            return load_lib($src);
        }));
        $twig->addFunction(new TwigFunction('static', function ($src) {
            return load_asset($src);
        }));

        if ($config['debug'] ?? '') {
            $twig->addExtension(new \Twig\Extension\DebugExtension());
        }
        $twig->addGlobal('seecms_lang', SeeLang::instance()->getLangSet());

        return self::$instance = $twig;
    }

    /**
     * 获取twig实例
     * @return Twig
     */
    public static function instance(): Twig
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }

        return self::$instance;
    }
}